<template>
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="500px"
      draggable
      @close="closeDialog"
      :close-on-click-modal="false"
      destroy-on-close
      align-center
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        v-loading="loading1"
        label-width="90px"
        style="display: flex"
      >
        <el-row>
          <el-col :span="23">
            <el-form-item label="供应商" prop="partnerId">
              <el-select
                @change="partnerChange"
                v-model="formData.partnerId"
                placeholder="请选择"
                style="width: 100%"
                :disabled="disabled"
              >
                <el-option
                  v-for="item in partners"
                  :key="item.id"
                  :label="item.partnerName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!--物料号  @click="clickMaterial"  -->
          <el-col :span="23">
            <el-form-item label="物料" prop="materialId">
              <!-- <el-input
                :disabled="formData.partnerId == ''"
                v-model="formData.materialName"
                placeholder="请输入物料"
                style="width: 100%"
                @click="clickMaterial"
              >
              </el-input> -->
              <el-select
                @click="clickMaterial"
                v-model="formData.materialId"
                placeholder="请选择物料"
                style="width: 100%"
                :disabled="formData.partnerId == ''"
              >
                <el-option
                  v-for="item in breakList"
                  :key="item.materialId"
                  :label="item.materialName"
                  :value="item.materialId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="23">
            <el-form-item label="卸货口" prop="dischargeHatchId">
              <el-select
                @change="dischargehatchChange"
                v-model="formData.dischargeHatchId"
                placeholder="请选择卸货口"
                style="width: 100%"
                :disabled="disabled"
              >
                <el-option
                  v-for="item in dischargehatchs"
                  :key="item.id"
                  :label="
                    item.dischargeHatchCode + '-' + item.dischargeHatchName
                  "
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="23">
            <el-form-item label="要货日期" prop="demandDate">
              <el-date-picker
                v-model="formData.demandDate"
                :disabled-date="disabledDate"
                style="width: 100%"
                type="date"
                placeholder="请选择要货日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="23">
            <el-form-item label="要货数量" prop="demandQuantity">
              <el-input-number
                v-model="formData.demandQuantity"
                :min="1"
                :precision="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer v-if="!loading1">
        <div class="dialog-footer">
          <el-button type="primary" :loading="loading" @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>

      <demo-purchase-select-material-dialog
        :visible="selectDialog.visible"
        :breakList="breakList ? breakList : []"
        @change-visible="changeVisible"
        :partnerId="formData.partnerId"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import dayjs from "dayjs";

defineOptions({
  name: "PLANGOODSADDNEWDIALOG",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  beginDate: {
    type: String,
    default: () => {
      return "";
    },
  },
  endDate: {
    type: String,
    default: () => {
      return "";
    },
  },
});
const disabled = ref(false);
const loading1 = ref(false);
const visibleDialog = ref(false);

// 工厂
let plants: any = ref([]);
// 物料号
let materials: any = ref([]);
// 供应商
let partners: any = ref([]);
// 卸货口
let dischargehatchs: any = ref([]);

// 选择物料弹窗
const selectDialog: any = reactive({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  partnerId: "",
  breakList: [],
});
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;

    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

// 表单校验规则
const rules = reactive({
  plantId: [{ required: true, message: "未选择工厂", trigger: "change" }],
  partnerId: [{ required: true, message: "未选择供应商", trigger: "change" }],
  arriveDate: [
    {
      required: true,
      type: "date",
      message: "未选择到货日期",
      trigger: "change",
    },
  ],
  demandDate: [
    {
      required: true,
      message: "未选择要货日期",
      trigger: "change",
    },
  ],
  materialId: [{ required: true, message: "未选择物料", trigger: "blur" }],
  storageLocationName: [
    { required: true, message: "未选择要货地点", trigger: "change" },
  ],
  planQuantity: [
    { required: true, message: "未输入要货数量", trigger: "change" },
  ],
  dischargeHatchId: [
    { required: true, message: "未选择卸货口", trigger: "change" },
  ],
  purchasePlanNumber: [
    { required: true, message: "未选择采购协议", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  beginDate: [],
  endDate: [],
  filename: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  dischargeHatchId: "",
  dischargeHatchCode: "",
  dischargeHatchName: "",
  dischargeHatchAbbr: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  // 需求日期
  demandDate: "",
  // 需求数量
  demandQuantity: 0,
  // 需求日期（格式化）
  demandDateShow: "",
  // 计划id
  planId: "",
});

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.partnerName = "";
  formData.dischargeHatchId = "";
  formData.dischargeHatchCode = "";
  formData.dischargeHatchName = "";
  formData.dischargeHatchAbbr = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  // 需求日期
  formData.demandDate = "";
  // 需求数量
  formData.demandQuantity = 0;
  // 需求日期（格式化）
  formData.demandDateShow = "";
  // 计划id
  formData.planId = "";
  disabled.value = false;
}

const loading = ref(false);

// 禁用当前日期之前日期(不包含当天日期)
const disabledDate = (time: Date) => {
  if (time.getTime() > dayjs(props.endDate).valueOf()) {
    return true;
  }
  if (time.getTime() < dayjs(props.beginDate).valueOf()) {
    return true;
  }
  return false;
};

/** 订货计划保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = "新增";
      await request({
        url: "/srm/srmdemandschedule/addItem",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

onMounted(() => {
  // getPartners();
  // getDischargehatchs();
});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 供应商查询
async function getPartners() {
  const data = await request({
    url: "/srm/core/mdmpartner/getList",
    method: "post",
    data: {},
  });
  partners.value = data.data;
}

// 改变供应商
function partnerChange() {
  materials.value = [];
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  const partner = partners.value.find((item) => {
    return item.id === formData.partnerId;
  });
  formData.partnerCode = partner.partnerCode;
  formData.partnerName = partner.partnerName;
  getMaterials();
}

async function getMaterials() {
  const data = await request({
    url: `/srm/core/partnerproduct/materialList/` + formData.partnerId,
    method: "get",
  });
  materials.value = data.data;
}

async function getDischargehatchs() {
  const data = await request({
    url: `/srm/srmdischargehatch/getDropdownList/${formData.plantId}`,
    method: "get",
  });
  dischargehatchs.value = data.data;
}

// 改变卸货口
function dischargehatchChange() {
  const dischargehatch = dischargehatchs.value.find((item) => {
    return item.id === formData.dischargeHatchId;
  });
  formData.dischargeHatchCode = dischargehatch.dischargeHatchCode;
  formData.dischargeHatchName = dischargehatch.dischargeHatchName;
  formData.dischargeHatchAbbr = dischargehatch.dischargeHatchAbbr;
  formData.plantId = dischargehatch.plantId;
  formData.plantCode = dischargehatch.plantCode;
  formData.plantName = dischargehatch.plantName;
}

const breakList = ref([]);
const changeVisible = (val: boolean, data: any) => {
  if (data) {
    breakList.value = [];
    breakList.value.push(data);
    formData.materialId = data.materialId;
    formData.materialCode = data.materialCode;
    formData.materialName = data.materialName;
  }
  selectDialog.visible = val;
};

// 点击物料之后弹窗选择
const clickMaterial = () => {
  if (formData.partnerId) {
    selectDialog.title = "选择物料";
    selectDialog.partnerId = formData.partnerId;
    selectDialog.breakList = breakList.value ? breakList.value : [];
    selectDialog.visible = true;
  }
};
</script>
